import React from 'react';
import { Link } from 'dva/router';
import { Carousel } from 'antd-mobile';

class Slider extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      imgHeight: 176,
    };
  }

  render() {
    const props = this.props;
    const autoplay = Object.prototype.hasOwnProperty.call(props, 'autoplay')
      ? props.autoplay : false;

    const infinite = Object.prototype.hasOwnProperty.call(props, 'infinite')
      ? props.infinite : false;

    const keyOf = inx => `carousel-${inx}`;

    return (
      <Carousel
        autoplay={autoplay}
        infinite={infinite}
      >
        {
          (props.items || []).map((item, inx) => {
            const { link, image } = item;

            return (
              <Link
                key={keyOf(inx)}
                to={link}
                style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
              >
                <img
                  src={image}
                  alt=""
                  style={{ width: '100%', verticalAlign: 'top' }}
                  onLoad={() => {
                    // fire window resize event to change height
                    window.dispatchEvent(new window.Event('resize'));
                    this.setState({ imgHeight: 'auto' });
                  }}
                />
              </Link>
            );
          })
        }
      </Carousel>
    );
  }
}

export default Slider;
